// Copyright 2022 a.o.smith ALL Rights Reserved
package com.liuxinlong.modules.patent.service.impl;

import com.liuxinlong.common.AosException;
import com.liuxinlong.common.SnowFlake;
import com.liuxinlong.enums.ReturnCodes;
import com.liuxinlong.modules.dao.FileManageDao;
import com.liuxinlong.modules.dao.PatentCarouselDao;
import com.liuxinlong.modules.entity.PatentCarousel;
import com.liuxinlong.modules.patent.service.PatentCarouselService;
import com.liuxinlong.modules.system.service.FileManageService;
import com.liuxinlong.utils.IPUtils;
import com.liuxinlong.utils.ObjectUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 专利轮播图实现类
 *
 * @author liuxinlong@hotwater.com.cn
 * @version 1.0.0
 * @since 2023-09-27
 */
@Service
@Slf4j
public class PatentCarouselServiceImpl implements PatentCarouselService {

    @Autowired
    private PatentCarouselDao patentCarouselDao;

    @Autowired
    private FileManageDao fileManageDao;

    @Autowired
    private FileManageService fileManageService;

    @Override
    public List<Map<String, Object>> queryPatentCarouselList(Map<String, Object> queryParam) {
        int startNum = (int) queryParam.get("startNum");
        List<PatentCarousel> originalList = patentCarouselDao.pagePatentCarouselList(queryParam);
        return completeResult(originalList, startNum);
    }

    @Override
    public int getPatentCarouselCount(Map<String, Object> queryParam) {
        return patentCarouselDao.getPatentCarouselCount(queryParam);
    }

    @Override
    public void addPatentCarousel(PatentCarousel patentCarousel) {
        String id = SnowFlake.nextIdStr();
        patentCarousel.setId(id);
        patentCarouselDao.insert(patentCarousel);
        List<String> pictureList = new ArrayList<>();
        if (!StringUtils.isEmpty(patentCarousel.getPicture())) {
            pictureList.add(patentCarousel.getPicture());
        }
        fileManageService.updateBusinessFile(StringUtils.strip(pictureList.toString(),"[]").replaceAll(" +",""), id);
    }

    @Override
    public void updatePatentCarousel(PatentCarousel patentCarousel) {
        String id = patentCarousel.getId();
        if (StringUtils.isEmpty(id)) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "修改轮播信息异常，轮播不存在！");
        }
        PatentCarousel oldInfo = patentCarouselDao.selectById(id);
        if (ObjectUtils.isEmpty(oldInfo)) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "修改轮播信息异常，轮播不存在！");
        }
        patentCarouselDao.updateById(patentCarousel);
        if (StringUtils.equals(oldInfo.getPicture(),patentCarousel.getPicture())) {
            return;
        }
        List<String> pictureList = new ArrayList<>();
        if (!StringUtils.isEmpty(patentCarousel.getPicture())) {
            pictureList.add(patentCarousel.getPicture());
        }
        fileManageService.updateBusinessFile(StringUtils.strip(pictureList.toString(),"[]").replaceAll(" +",""), id);
    }

    @Override
    public void deletePatentCarousel(String id) {
        if (StringUtils.isEmpty(id)) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "删除轮播信息异常，轮播不存在！");
        }
        PatentCarousel oldInfo = patentCarouselDao.selectById(id);
        if (ObjectUtils.isEmpty(oldInfo)) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "删除轮播信息异常，轮播不存在！");
        }
        fileManageService.batchInvalidFile(id);
        patentCarouselDao.deleteById(id);
    }

    @Override
    public void updatePatentCarouselStatus(String id) {
        if (StringUtils.isEmpty(id)) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "修改轮播状态异常，轮播信息不存在！");
        }
        PatentCarousel oldInfo = patentCarouselDao.selectById(id);
        if (ObjectUtils.isEmpty(oldInfo)) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "修改轮播状态异常，轮播信息不存在！");
        }
        // 目标状态 1 启用 0 停用
        int targetStatus = oldInfo.getStatus() == 0 ? 1 : 0;
        if (targetStatus == 1) {
            PatentCarousel effectInfo = patentCarouselDao.getCarouselByIndex(oldInfo.getShowIndex());
            if (!ObjectUtils.isEmpty(effectInfo)) {
                patentCarouselDao.updateCarouselStatus(effectInfo.getId(), 0);
            }
        }
        patentCarouselDao.updateCarouselStatus(id, targetStatus);
    }

    /**
     * 数据补全转换
     *
     * @param originList 原始数据列表
     * @param startNum   起始查询数
     * @return 补全数据
     */
    private List<Map<String, Object>> completeResult(List<PatentCarousel> originList, int startNum) {
        if (ObjectUtils.isEmpty(originList)) {
            return new ArrayList<>();
        }
        Set<String> fileIdList = new HashSet<>();
        Set<String> pictureIdList = originList.stream().map(PatentCarousel::getPicture).collect(Collectors.toSet());
        fileIdList.addAll(pictureIdList);
        Map<String,Map<String,Object>> fileMap = new HashMap<>();
        if (!ObjectUtils.isEmpty(fileIdList)) {
            fileMap = fileManageDao.getFileMapByIds(fileIdList);
        }
        String currentIp = IPUtils.getCurrentIp();
        List<Map<String, Object>> resultList = new ArrayList<>(originList.size());
        int sort = startNum + 1;
        for (PatentCarousel record : originList) {
            Map<String, Object> map = ObjectUtils.object2Map(record);
            map.put("sort", sort);
            if (!StringUtils.isEmpty(record.getPicture())) {
                String filePath = fileMap.containsKey(record.getPicture()) ? (String) fileMap.get(record.getPicture()).get("path") : "";
                String path = StringUtils.isEmpty(filePath) ? "" : filePath.replace("upload", "http:\\\\" + currentIp + ":8090\\preview\\upload");
                map.put("pictureUrl",path);
            }
            resultList.add(map);
            sort++;
        }
        return resultList;
    }
}
